package com.cheyun.netsalev3.viewmodel

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.Looper
import android.view.View
import com.cheyun.netsalev3.bean.login.LoginParam
import com.cheyun.netsalev3.repository.LoginRepository
import com.cheyun.netsalev3.utils.api.DmApiClient
import com.cheyun.netsalev3.utils.api.DmBaseResp
import com.cheyun.netsalev3.utils.api.dm.DmApiCallback
import com.cheyun.netsalev3.utils.api.dm.DmApiException
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import android.view.Gravity
import android.view.ViewGroup
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.MyApplication
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.tencenttim.signature.GenerateTestUserSig
import com.cheyun.netsalev3.tencenttim.thirdpush.ThirdPushTokenMgr
import com.cheyun.netsalev3.tencenttim.utils.DemoLog
import com.cheyun.netsalev3.utils.*
import com.cheyun.netsalev3.view.*
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tencent.imsdk.TIMManager
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack


/**
 * @author Michael
 * @date  2018/12/6 - 10:48.
 */
class LoginActivityViewModel : BaseViewModel() {
    var password: String = MySharedPreferences.getPassword()
    var mobile: String = MySharedPreferences.getMobile()
    var version:String = ""
    private var loginRepository = LoginRepository()
    var showPwd = MutableLiveData<Boolean>()

    var activity: Activity? = null
    var agree = MutableLiveData<Boolean>(false)

    init {
        var ys = MySharedPreferences.getYsChecked()
        agree.postValue(ys.equals("1"))
    }

    fun onClickLogin(view: View) {
        if (CommonFunc.isBlank(mobile)) {
            MyToast("请输入手机号")
            return;
        }
        if (CommonFunc.isBlank(password)) {
            MyToast("请输入登录密码")
            return
        }
        if (!agree.value!!) {
            MyToast("请阅读并同意隐私协议")
            return
        }
        loginRepository.Login(mobile, password, this::setData,this::goDm)
    }
    fun onPasViewClick(view:View){
        this.showPwd.postValue(!showPwd.value!!)
    }

    /**
     * 登陆请求数据回调
     */
    fun setData(param: LoginParam) {
        param.cauthkey?.apply {
            MySharedPreferences.putCauthkey(this)
            MySharedPreferences.putMobile(mobile)
            MySharedPreferences.putPassword(password)
            MySharedPreferences.putLoginData(param)
        }
        //还没有加入任何通道
        if(param.member.uid == 0){
            var intent = MyIntent(BindDistributorActivity::class.java)
            intent.putExtra("single",true)
            myStartActivity(intent)
            myFinish()
            MyToast("登录成功，请等待管理员审核通过")
            return
        }
//        //当前通道是否是2s店员工登录到4s店
//        if(param.channel.is2sdms == 1){
//            var intent = MyIntent(BindDistributorActivity::class.java)
//            intent.putExtra("single",true)
//            myStartActivity(intent)
//            myFinish()
////            MyToast("登录成功，请等待管理员审核通过")
//            return
//        }
        param.member?.workbench?.apply {
            MySharedPreferences.setWorkbench(this)
        }
        param.member?.uconfig?.notice?.apply {
            MySharedPreferences.putNotice(this)
        }
        loginRepository.basData()
        goCrm()
    }

//    fun timLogin(){
//        val userSig = GenerateTestUserSig.genTestUserSig(mobile)
//        TUIKit.login(mobile, userSig, object : IUIKitCallBack {
//            override fun onError(module: String, code: Int, desc: String) {
//                DemoLog.i("tim login", "imLogin errorCode = $code, errorInfo = $desc")
//            }
//
//            override fun onSuccess(data: Any?) {
//                DemoLog.i("tim login", "imLogin success")
//                var unreadMessageNum = 0
//                var msgList = TIMManager.getInstance().conversationList
//                if(msgList.size>0){
//                    for (i in 0 until msgList.size){
//                        unreadMessageNum = unreadMessageNum + msgList[i].unreadMessageNum.toInt()
//                    }
//                }
//                LiveEventBus.get().with("chatNum").postValue(unreadMessageNum)
//                DmApiClient.getInstance().kefuBusy(mobile,"0")
//                        .subscribeOn(Schedulers.io())
//                        .subscribeOn(AndroidSchedulers.mainThread())
//                        .subscribe(object : DmApiCallback<DmBaseResp<Any, Any>>() {
//                            override fun onSuccess(t: DmBaseResp<Any, Any>) {
//                                MyApplication.getInstance().setTimOffline(false)
//                                MyApplication.getInstance().setTimBusying(false)
//                            }
//
//                            override fun onError(ex: DmApiException) {
//
//                            }
//                        })
//
////                ThirdRegIdMgr.prepareThirdPushToken(activity)
//                ThirdPushTokenMgr.getInstance().setPushTokenToTIM();
//            }
//        })
//    }
    fun goCrm(){
//        timLogin()
        var intent = MyIntent(MainActivity::class.java)
        myStartActivity(intent)
        myFinish()
        MyToast("登录成功")
    }

    fun goDm(key:String){
        MySharedPreferences.putMobile(mobile)
        MySharedPreferences.putPassword(password)
//        timLogin()
        var intent = MyIntent(ModuleActivity::class.java)
        intent.putExtra("key",key)
        myStartActivity(intent)
        myFinish()
    }

    fun forget() {
        myStartActivity(MyIntent(ForgetActivity::class.java))
    }

    fun register() {
        myStartActivity(MyIntent(RegisterActivity::class.java))
    }

    fun showYs(view:View){
//        val bottomDialog = Dialog(view.context, R.style.BottomDialog)
//        val contentView = LayoutInflater.from(view.context).inflate(R.layout.dialog_content_circle, null)
//        bottomDialog.setContentView(contentView)
//
//        val webView = contentView.findViewById<WebView>(R.id.detail_webview)
//        webView.settings.javaScriptEnabled = true
//        webView.settings.domStorageEnabled = true
//        webView.loadUrl(ApiStores.XIEYI_URL)
//
//        val params = contentView.getLayoutParams() as ViewGroup.MarginLayoutParams
//        params.width = view.context.getResources().getDisplayMetrics().widthPixels - FunctionUtils.dip2px(view.context, 16f)
//        params.bottomMargin = FunctionUtils.dip2px(view.context, 8f)
//        contentView.setLayoutParams(params)
//        bottomDialog.getWindow().setGravity(Gravity.BOTTOM)
//        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation)
//        bottomDialog.show()
        val bottomDialog = Dialog(view.context, R.style.BottomDialog)
        val contentView = LayoutInflater.from(view.context).inflate(R.layout.dialog_content_circle, null)
        bottomDialog.setContentView(contentView)
        val params = contentView.getLayoutParams() as ViewGroup.MarginLayoutParams
        params.width = view.context.getResources().getDisplayMetrics().widthPixels - FunctionUtils.dip2px(view.context, 16f)
        params.topMargin = DensityUtil.dip2px(view.context, 20f)
        params.bottomMargin = DensityUtil.dip2px(view.context, 20f)
        contentView.setLayoutParams(params)
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM)
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation)
        bottomDialog.show()

        var llWin = contentView.findViewById<LinearLayout>(R.id.ll_win)
        llWin.setOnClickListener { bottomDialog.dismiss() }
    }

    fun onAgree(view: View) {
        agree.postValue(!agree.value!!)
    }

}